package de.fme.publishing;

import org.alfresco.service.cmr.publishing.PublishingEvent;
import org.alfresco.service.cmr.publishing.channels.ChannelService;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;

import de.fme.tracking.TrackingModel;

/**
 * For Yammer and Twitter Publishing
 * Facebook handles this on its own
 * 
 * @author JUP
 * @since 4.0
 */

public class PublishingInfoHelper
{
	private NodeService nodeService;
	
	/**
	 * Add StatusUpdateId to publishing Event by EVENT
	 * @param event
	 * @param statusUpdateId
	 */
	public void addStatusUpdateId(PublishingEvent event, String statusUpdateId){
		NodeRef pubEventNode = getEventNodeRef(event);
		addStatusUpdateId(pubEventNode, statusUpdateId);
	}
	
	/**
	 * Add StatusUpdateId to publishing Event BY NODEREF
	 * @param pubEventNode NodeRef
	 * @param statusUpdateId
	 */
	public void addStatusUpdateId(NodeRef pubEventNode, String statusUpdateId){
		if(!nodeService.hasAspect(pubEventNode, TrackingModel.ASPECT_STATUS_MESSAGE)){
        	nodeService.addAspect(pubEventNode, TrackingModel.ASPECT_STATUS_MESSAGE, null);
        }
		nodeService.setProperty(pubEventNode, TrackingModel.PROP_STATUS_MESSAGE_ID, statusUpdateId);
	}
	
	/**
	 * Add shortUrl and the long URL of published asset to publishing event BY EVENT
	 * @param event
	 * @param nodeUrl
	 */
	public void addUrlsToPubEvent(PublishingEvent event, String nodeUrl){
		NodeRef pubEventNode = getEventNodeRef(event);
		addShortUrlToPubEvent(pubEventNode, nodeUrl);
	}
	
	/**
	 * Add shortUrl and the long URL of published asset to publishing event BY NODEREF
	 * @param pubEventNode
	 * @param url
	 */
	public void addShortUrlToPubEvent(NodeRef pubEventNode, String url){
		if(!nodeService.hasAspect(pubEventNode, TrackingModel.ASPECT_ASSET)){
        	nodeService.addAspect(pubEventNode, TrackingModel.ASPECT_ASSET, null);
        }
		nodeService.setProperty(pubEventNode, TrackingModel.PROP_ASSET_LONG_URL, url);
	}
	
	/**
	 * Helper Method to get the NodeRef from the Publishing Event
	 * The eventId equals the nodeUUID which is the identifier of the NodeRef
	 * @param event
	 * @return
	 */
    private NodeRef getEventNodeRef(PublishingEvent event) {
    	NodeRef eventNodeRef = null;
		String eventId = event.getId();
		if (NodeRef.isNodeRef(eventId)){
			eventNodeRef = new NodeRef (eventId);
		}else{
			eventNodeRef = nodeService.getNodeRef(Long.parseLong(eventId));
		}
		return eventNodeRef;
	}
    
    public void setNodeService(NodeService nodeService) {
		this.nodeService = nodeService;
	}
}
